package com.meiyuetao.myt.kuajing.service;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import lab.s2jh.core.dao.BaseDao;
import lab.s2jh.core.service.BaseService;
import lab.s2jh.core.util.DateUtils;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import com.meiyuetao.myt.kuajing.dao.KjOrderInfoDao;
import com.meiyuetao.myt.kuajing.entity.KjOrderDetailInfo;
import com.meiyuetao.myt.kuajing.entity.KjOrderInfo;
import com.meiyuetao.myt.md.entity.Commodity;
import com.meiyuetao.myt.sale.dao.BoxOrderDao;
import com.meiyuetao.myt.sale.entity.BoxOrder;
import com.meiyuetao.myt.sale.entity.BoxOrder.KuaJingStatusEnum;
import com.meiyuetao.myt.sale.entity.BoxOrderDetail;
import com.meiyuetao.myt.sale.entity.BoxOrderDetailCommodity;

@Service
@Transactional
public class KjOrderInfoService extends BaseService<KjOrderInfo, Long> {

    @Autowired
    private KjOrderInfoDao kjOrderInfoDao;
    @Autowired
    private BoxOrderDao boxOrderDao;

    @Override
    protected BaseDao<KjOrderInfo, Long> getEntityDao() {
        return kjOrderInfoDao;
    }

    @Value("${kuaJing.orderSendUrl}")
    private String orderSendUrl;
    @Value("${kuaJing.userName}")
    private String userName;
    @Value("${kuaJing.passWord}")
    private String passWord;

    public void sendToKuaJing(BoxOrder boxOrder) {
        KjOrderInfo kjOrderInfo = initKjOrderInfo(boxOrder);
        String xmlString = generateOrderInfoXml(kjOrderInfo);
        String postData = "";
        try {
            postData = new String(Base64.encodeBase64(xmlString.getBytes()), "utf-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        // String response = null;
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        CloseableHttpClient client = httpClientBuilder.build();
        HttpPost httpPost = new HttpPost(orderSendUrl);
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        formparams.add(new BasicNameValuePair("data", postData));
        UrlEncodedFormEntity entity;
        // 设置Post数据

        try {
            entity = new UrlEncodedFormEntity(formparams, "UTF-8");
            httpPost.setEntity(entity);
            HttpResponse httpResponse;
            // post请求
            httpResponse = client.execute(httpPost);
            int status = httpResponse.getStatusLine().getStatusCode();
            if (HttpStatus.SC_OK == status) {
                boxOrder.setKuaJingStatus(KuaJingStatusEnum.SEND);
                boxOrderDao.save(boxOrder);
            }
            client.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private KjOrderInfo initKjOrderInfo(BoxOrder boxOrder) {
        KjOrderInfo kjOrderInfo = new KjOrderInfo();
        kjOrderInfo.setCustomersCode("8013");
        kjOrderInfo.setBizTypeCode("I10");
        kjOrderInfo.setOriginalOrderNo(boxOrder.getOrderSeq());
        kjOrderInfo.setReceiverName(boxOrder.getReceivePerson());
        kjOrderInfo.setReceiverTel(boxOrder.getMobilePhone());
        kjOrderInfo.setReceiverAddress(boxOrder.getDeliveryAddr());
        kjOrderInfo.setGoodsFee(boxOrder.getActualAmount());
        List<KjOrderDetailInfo> kjOrderDetailInfos = kjOrderInfo.getKjOrderDetailInfos();
        BoxOrderDetail boxOrderDetail = boxOrder.getBoxOrderDetails().get(0);
        for (BoxOrderDetailCommodity item : boxOrderDetail.getBoxOrderDetailCommodities()) {
            KjOrderDetailInfo kjOrderDetailInfo = new KjOrderDetailInfo();
            Commodity commodity = item.getCommodity();
            kjOrderDetailInfo.setSku(commodity.getSku());
            kjOrderDetailInfo.setGoodsSpec(commodity.getSpec());
            kjOrderDetailInfo.setPrice(item.getPrice());
            kjOrderDetailInfo.setQty(item.getQuantity());
            kjOrderDetailInfo.setGoodsFee(kjOrderDetailInfo.getPrice().multiply(kjOrderDetailInfo.getQty()));
            kjOrderDetailInfo.setKjOrderInfo(kjOrderInfo);
            kjOrderDetailInfos.add(kjOrderDetailInfo);
        }
        return kjOrderInfo;
    }

    private String generateOrderInfoXml(KjOrderInfo kjOrderInfo) {
        String uuid = UUID.randomUUID().toString();
        String md5Pwd = DigestUtils.md5DigestAsHex((uuid + passWord).getBytes());
        String xmlString = "<?xml version='1.0' encoding='utf-8'?><DTC_Message>" + "<MessageHead>" + " <MessageType>ORDER_INFO</MessageType>" + "<MessageId>" + uuid
                + "</MessageId>" + "<ActionType>1</ActionType>" + "<MessageTime>" + DateUtils.formatTime(new Date()) + "</MessageTime>" + " <SenderId>" + userName + "</SenderId>"
                + " <ReceiverId>CQITC</ReceiverId>" + " <UserNo>" + userName + "</UserNo>" + " <Password>" + md5Pwd + "</Password>" + "</MessageHead>" + " <MessageBody>"
                + " <DTCFlow>" + " <ORDER_HEAD>" + " <CUSTOMS_CODE>8013</CUSTOMS_CODE>" + " <BIZ_TYPE_CODE>I10</BIZ_TYPE_CODE>"
                + " <ORIGINAL_ORDER_NO>201409241724</ORIGINAL_ORDER_NO>" + "<ESHOP_ENT_CODE>" + userName + "</ESHOP_ENT_CODE>" + " <ESHOP_ENT_NAME>" + "MEIYUETAO"
                + "</ESHOP_ENT_NAME>" + "<DESP_ARRI_COUNTRY_CODE>324</DESP_ARRI_COUNTRY_CODE>" + "<SHIP_TOOL_CODE>Y</SHIP_TOOL_CODE>"
                + "<RECEIVER_ID_NO>500226198710271112</RECEIVER_ID_NO>" + "<RECEIVER_NAME>庄挺</RECEIVER_NAME>" + "<RECEIVER_ADDRESS>重庆重庆寸滩保税港区水港综合楼1604室</RECEIVER_ADDRESS>"
                + "<RECEIVER_TEL>13983892879</RECEIVER_TEL>" + "<GOODS_FEE>0.01</GOODS_FEE>" + "<TAX_FEE>0</TAX_FEE>" + "<GROSS_WEIGHT>0.6</GROSS_WEIGHT>"
                + "<SORTLINE_ID>SORTLINE02</SORTLINE_ID>" + "<ORDER_DETAIL>" + "<SKU>1234599999I000924063</SKU>" + "<GOODS_SPEC>GDS-768G</GOODS_SPEC>"
                + "<CURRENCY_CODE>142</CURRENCY_CODE>" + "<PRICE>0.01</PRICE>" + "<QTY>1</QTY>" + "<GOODS_FEE>0.01</GOODS_FEE>" + "<TAX_FEE>0</TAX_FEE>" + "</ORDER_DETAIL>"
                + "</ORDER_HEAD>" + "</DTCFlow>" + "</MessageBody>" + "</DTC_Message>";
        return xmlString;
    }

}
